package com.ant.storage.controller;


import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.SubjectDto;
import com.ant.storage.pojo.SubjectManagement;
import com.ant.storage.service.ISubjectManagementService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author melon
 * @since 2023-11-10
 */
@RestController
@RequestMapping("/SubjectManagement")
public class SubjectManagementController {


    @Autowired
    private ISubjectManagementService typeService;

    @ApiOperation(value = "获取科目主体数据列表")
    @GetMapping("/list")
    public ResultVo list(SubjectDto dto) {
        List<SubjectManagement> list;
        if(dto.getSubjectCode() == null){
           list = typeService.list();
        }else{
            list = typeService.list(new QueryWrapper<SubjectManagement>().eq("subject_code", dto.getSubjectCode()));
        }

        //        获取根节点
        List<SubjectManagement> Departments = list.stream()
                .filter(e -> e.getParent()==0)
                .map(e -> {
                    if(getTreeChildren(e, list).size()>0){
                        e.setChildren(getTreeChildren(e, list));
                    }else{
                        e.setChildren(null);
                    }
                    return e;
                }).collect(Collectors.toList());
        return ResultVo.success("获取成功",Departments);

    }


    private List<SubjectManagement> getTreeChildren(SubjectManagement e, List<SubjectManagement> list) {
        List<SubjectManagement> children = list.stream()
                .filter(m -> Objects.equals(e.getId(), m.getParent()))
                .map(m -> {
                    if(getTreeChildren(m, list).size()>0){
                        m.setChildren(getTreeChildren(m, list));
                    }else {
                        m.setChildren(null);
                    }
                    return m;
                }).collect(Collectors.toList());
        return children;
    }

    @ApiOperation(value = "保存主体")
    @PostMapping("/save")
    public ResultVo save(@RequestBody SubjectManagement type) {
        if (type.getId() == null) {
            typeService.save(type);
        } else {
            typeService.updateById(type);
        }
        return ResultVo.success("获取成功");
    }

}
